package com.carlo.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import microsoft.exchange.webservices.data.core.PropertySet;
import microsoft.exchange.webservices.data.core.enumeration.property.WellKnownFolderName;
import microsoft.exchange.webservices.data.core.enumeration.search.LogicalOperator;
import microsoft.exchange.webservices.data.core.enumeration.search.SortDirection;
import microsoft.exchange.webservices.data.core.enumeration.service.ConflictResolutionMode;
import microsoft.exchange.webservices.data.core.service.folder.Folder;
import microsoft.exchange.webservices.data.core.service.item.EmailMessage;
import microsoft.exchange.webservices.data.core.service.item.Item;
import microsoft.exchange.webservices.data.core.service.schema.EmailMessageSchema;
import microsoft.exchange.webservices.data.core.service.schema.ItemSchema;
import microsoft.exchange.webservices.data.property.complex.Attachment;
import microsoft.exchange.webservices.data.property.complex.FileAttachment;
import microsoft.exchange.webservices.data.search.FindItemsResults;
import microsoft.exchange.webservices.data.search.ItemView;
import microsoft.exchange.webservices.data.search.filter.SearchFilter;

import org.apache.commons.lang3.StringUtils;

import com.carlo.bean.MailCfg;
import com.carlo.bean.MailFilter;
import com.carlo.bean.MailInfo;
import com.carlo.service.AbstractMail;
import com.carlo.service.IReceive;
import com.carlo.util.GlobalUtil;

public class ExchangeReceiveImpl extends AbstractMail implements IReceive {
	
	public ExchangeReceiveImpl(String temp){
		this.temp = temp;
	}

	public List<MailInfo> receive(MailCfg mailCfg, MailFilter mailFilter)
			throws Exception {
		this.initExchangeService(mailCfg.getAccount(),mailCfg.getPwd(),mailCfg.getServer_name());
		return getUnreadEmails(mailFilter);
	}
	
	/**
	 * 
	* @Title: getUnreadEmails 
	* @Description: 获取满足条件的未读邮件 
	* @param @param mailFilter
	* @param @return
	* @param @throws Exception    设定文件 
	* @return ArrayList<MailInfo>    返回类型 
	* @author carlo
	* @throws
	 */
	public ArrayList<MailInfo> getUnreadEmails(MailFilter mailFilter) throws Exception {
        //绑定收件箱,同样可以绑定发件箱
        Folder inbox = Folder.bind(service, WellKnownFolderName.Inbox);
        //获取文件总数量
        ItemView view = new ItemView(Integer.MAX_VALUE);
        //按照时间顺序收取
        view.getOrderBy().add(ItemSchema.DateTimeReceived, SortDirection.Descending);
        FindItemsResults<Item> findResults;
        
        //获取未读邮件
		List<SearchFilter> searchFilterList = new ArrayList<SearchFilter>();
		searchFilterList.add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
		SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchFilterList);
		findResults = service.findItems(inbox.getId(), searchFilter, view);
		
        if(null ==  findResults || null == findResults.getItems() || findResults.getItems().isEmpty()){
        	return null;
        }
        service.loadPropertiesForItems(findResults, PropertySet.FirstClassProperties);
        ArrayList<MailInfo> result = new ArrayList<MailInfo>();
        List<EmailMessage> msgList = new ArrayList<EmailMessage>();
        for (Item item : findResults.getItems()) {
            EmailMessage message = (EmailMessage) item;
            String subject = message.getSubject();
            String body = GlobalUtil.clearHtmlLabel(message.getBody().toString());
            List<Attachment> attachs = null;
            if (message.getHasAttachments()) {
            	attachs = message.getAttachments().getItems();
            }
            
            if(!isSatisfy(subject ,body , attachs, mailFilter)){  //如果不满足过滤条件，则跳过
            	continue;  
            }
            
        	MailInfo mail = new MailInfo();
            mail.setSubject(subject);
            mail.setBody(body);
            List<File> attachments = new ArrayList<File>();
            if(null != attachs && !attachs.isEmpty()){
        		for(Attachment at : attachs){
        			String attachmentTempFile = this.temp + at.getName();
        			File tempFile  = new File(attachmentTempFile);
        			if (!tempFile.getParentFile().exists()) {  //判断父目录路径是否存在
        				tempFile.getParentFile().mkdirs();	//不存在则创建父目录
        				tempFile.createNewFile();
        			}
        			FileAttachment iAttachment = (FileAttachment) at;
                    iAttachment.load(attachmentTempFile);
                    attachments.add(tempFile);
        		}
        	}
            mail.setAttachments(attachments);
	        msgList.add(message);
	        result.add(mail);
        }
        
        //标记为已读
        if(!msgList.isEmpty()){
        	for(EmailMessage msg : msgList){
        		// 更新已读
    	        if (!msg.getIsRead()) {
    	        	msg.setIsRead(true);
    	        	msg.update(ConflictResolutionMode.AlwaysOverwrite);
//    	        	msg.delete(DeleteMode.MoveToDeletedItems);	 //把邮件移到已删除
    	        }
        	}
        }
        
        return result;
    }
	
	
	/**
	 * 
	* @Title: isSatisfy 
	* @Description: 邮件过滤 
	* @param @param subject
	* @param @param body
	* @param @param attachs
	* @param @param mailFilter
	* @param @return    设定文件 
	* @return boolean    返回类型 
	* @author carlo
	* @throws
	 */
	public boolean isSatisfy(String subject , String  body ,List<Attachment> attachs , MailFilter mailFilter){
		String subjectKeyWord = mailFilter.getSubjectKeyWord();
		String bodyKeyWord = mailFilter.getBodyKeyWord();
		String attachmentKeyWord = mailFilter.getAttachmentKeyWord();
		String attachmentFileType = mailFilter.getAttachmentFileType();
		
		boolean resultBoo = true;
		if(StringUtils.isNotBlank(subjectKeyWord)){
			if(mailFilter.isSubjectAdv()){  //正则匹配
				Pattern p = Pattern.compile(subjectKeyWord);
				Matcher m = p.matcher(subject);
				resultBoo = m.matches();
			}else{ //contain,字符串包含
				resultBoo = subject.contains(subjectKeyWord);
			}
		}
		if(!resultBoo){
			return false;
		}
		
		if(StringUtils.isNotBlank(bodyKeyWord)){
			if(mailFilter.isBodyAdv()){  //正则匹配
				Pattern p = Pattern.compile(bodyKeyWord);
				Matcher m = p.matcher(body);
				resultBoo = m.matches();
			}else{ //contain,字符串包含
				resultBoo = body.contains(bodyKeyWord);
			}
		}
		if(!resultBoo){
			return false;
		}
		
		if(StringUtils.isNotBlank(attachmentKeyWord)
				|| StringUtils.isNotBlank(attachmentFileType)){
			if(null != attachs && !attachs.isEmpty()){
				for(Attachment at : attachs){
					String attachFileName = at.getName(); 
	    			int index = attachFileName.lastIndexOf(".");
	    			String attachName = attachFileName.substring(0, index);
	    			//附件名
	    			if(StringUtils.isNotBlank(attachmentKeyWord)){
		    			if(mailFilter.isAttachmAdv()){  //正则匹配
		    				Pattern p = Pattern.compile(attachmentKeyWord);
		    				Matcher m = p.matcher(attachName);
		    				resultBoo = m.matches();
		    			}else{ //contain,字符串包含
		    				resultBoo = attachName.contains(attachmentKeyWord);
		    			}
	    			}
	    			if(resultBoo){  //附件名称符合过滤条件，再判断附件类型是否符合过滤条件
	    				if(StringUtils.isNotBlank(attachmentFileType)){
	    					resultBoo = attachFileName.endsWith(attachmentFileType);
	    				}
	    			}
	    			if(resultBoo){
	    				return true;
	    			}
	    		}
			}
		}
		
		return resultBoo;
	}
	

}
